//
//  FKOrderDetailVC.m
//  WanTao
//
//  Created by Macbook Pro on 2019/4/12.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "FKOrderDetailVC.h"
#import "FKOrderDetailStatusCell.h"
#import "FKOrderDetailInfoCell.h"
#import "FKOrderDetailHeader.h"
#import "FKOrder.h"
#import "FKOrderListCell.h"
#import "FKOrder.h"
#import "FKWeakTimer.h"
#import "FKPayMethodView.h"
#import "FKPayPwdInputView.h"
#import <AlipaySDK/AlipaySDK.h>
#import <WXApi.h> // 微信支付
#import "FKLookLogisticsVC.h"
#import "FKOrderEvaluateVC.h"
#import "FKSetPayPwdVC.h"
#import "FKApplyRefundVC.h"
#import "FKVerificationCodeVC.h"
#import "FKWeakTimer.h"
#import "FKDatePicker.h"
#import "FKChooseConsumeDateVC.h"

@interface FKOrderDetailVC ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, weak) UIView *bottomView;
@property (nonatomic, weak) UIButton *btn1;
@property (nonatomic, weak) UIButton *btn2;
@property (nonatomic, strong) FKOrder *orderDetail;
@property (nonatomic, copy) NSString *tel;
@property (nonatomic, assign) NSInteger countDown;

@end

@implementation FKOrderDetailVC
{
    NSTimer *timer;
}

- (void)dealloc
{
    [self removeTimer];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - private
- (void)startTimer
{
    [self removeTimer];
    timer = [FKWeakTimer fk_scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:true];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    [timer fire];
}

- (void)updateTime
{
    
    if (self.countDown > 0) {
        self.countDown--;
//        NSInteger miniute = self.countDown / 60;
//        NSInteger second = self.countDown % 60;
//        self.statusIntroLabel.text = fkFORMAT(@"剩%02zd分%02zd秒自动关闭", miniute, second);
    } else {
        [self removeTimer];
        [self loadData];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"updatePayCountDown" object:nil userInfo:@{@"countdown" : @(self.countDown)}];
}

- (void)removeTimer
{
    if (timer) [timer invalidate];
    timer = nil;
}

- (NSArray *)datas
{
    if (!_datas) {
        _datas = [NSArray array];
    }
    return _datas;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"订单详情";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"refreshOrderDetailVC" object:nil];
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIView *bottomView = [[UIView alloc] init];
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
//    bottomView.clipsToBounds = true;
    
    CGFloat btnW = fk_adjustW(75);
    CGFloat btnH = fk_adjustW(28);
    CGFloat btnX = fkScreenW - 12 - btnW;
    CGFloat btnY = (fk_adjustW(45) - btnH) * 0.5;
    for (NSInteger index = 0; index < 2; index++) {
        UIButton *btn = [UIButton fk_btnWithTarget:self action:@selector(operationBtnClicked:) img:nil];
        [self.bottomView addSubview:btn];
        btn.titleLabel.font = fk_adjustFont(13);
        [btn fk_viewCornerRadius:fk_adjustW(14) borderWidth:0.8 borderColor:fkColor666666];
        if (index != 0) btnX -= (btnW + fk_adjustW(15));
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
    }
    self.btn1 = self.bottomView.subviews.firstObject;
    self.btn2 = self.bottomView.subviews.lastObject;
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(fk_adjustW(45));
        make.left.right.offset(0);
        make.bottom.offset(fk_adjustW(45));
    }];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    
    [self loadData];
//    [self startTimer];
}

- (void)operationBtnClicked:(UIButton *)btn
{
    NSString *title = btn.titleLabel.text;
    fkWeakSelf(self);
    if ([title isEqualToString:@"去支付"]) {
        FKPayMethodView *view = [[FKPayMethodView alloc] init];
        view.amount = self.orderDetail.price;
        [view show];
        fkWeakSelf(view);
        view.selectePayMethodBlock = ^(NSString * _Nonnull payType) {
            if ([payType isEqualToString:@"balance"]) {
                if ([FKCacheTool isHasPayPwd]) { // 设置了支付密码
                    FKPayPwdInputView *pwdView = [[FKPayPwdInputView alloc] init];
                    [pwdView show];
                    pwdView.inputFinishBlock = ^(NSString *pwd) {
                        [weakself createPayInfo:payType orderSn:self.orderDetail.order_sn amount:self.orderDetail.settle_price pwd:pwd];
                    };
                } else { // 没有设置支付密码
                    FKSetPayPwdVC *vc = [[FKSetPayPwdVC alloc] init];
                    [weakself.navigationController pushViewController:vc animated:true];
                }
            } else {
                [weakself createPayInfo:payType orderSn:self.orderDetail.order_sn amount:self.orderDetail.settle_price pwd:nil];
            }
            [weakview dismiss];
        };
    } else if ([title isEqualToString:@"取消订单"]) {
        [self fk_alertWithTitle:@"确定要取消订单吗？" confirm:^{
            [weakself cancelGoodsOrder];
        }];
    } else if ([title isEqualToString:@"确认收货"]) {
        [self fk_alertWithTitle:@"是否确认收货？" confirm:^{
            [weakself confirmReceive];
        }];
    } else if ([title isEqualToString:@"查看物流"]) {
        FKLookLogisticsVC *vc = [[FKLookLogisticsVC alloc] init];
        vc.orderId = self.order_id;
        [weakself.navigationController pushViewController:vc animated:true];
    } else if ([title isEqualToString:@"去评价"]) {
        FKOrderEvaluateVC *vc = [[FKOrderEvaluateVC alloc] init];
        vc.orderId = self.order_id;
        [weakself.navigationController pushViewController:vc animated:true];
    } else if ([title isEqualToString:@"删除订单"]) {
        [self fk_alertWithTitle:@"确定要删除订单吗？" confirm:^{
            [weakself deleteOrder];
        }];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *group = self.datas[section];
    NSArray *items = group[@"items"];
    return items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *group = self.datas[indexPath.section];
    NSArray *items = group[@"items"];
    NSDictionary *item = items[indexPath.row];
    FKTableCell *cell = [FKTableCell cellWith:tableView className:item[@"cellName"]];
    cell.data = item[@"data"];
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *group = self.datas[indexPath.section];
    NSArray *items = group[@"items"];
    NSDictionary *item = items[indexPath.row];
    return [item[@"cellH"] floatValue];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    NSDictionary *group = self.datas[section];
    return group[@"headerH"] ? [group[@"headerH"] floatValue] : 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    FKOrderDetailHeader *header = [FKOrderDetailHeader sectionView:tableView];
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - FKOrderListCellDelegate
- (void)orderListCell:(FKOrderListCell *)cell didClickedItemBtn:(FKOrderGoods *)goods title:(NSString *)title
{
    if ([title isEqualToString:@"退款"]) {
        FKApplyRefundVC *vc = [[FKApplyRefundVC alloc] init];
        vc.goodsId = goods.id;
        fkPushNav(vc);
    } else if ([title isEqualToString:@"核销"]) {
        FKVerificationCodeVC *vc = [[FKVerificationCodeVC alloc] init];
        vc.order_goods_id = goods.id;
        fkPushNav(vc);
    } else if ([title isEqualToString:@"预约"]) {
        FKChooseConsumeDateVC *vc = [[FKChooseConsumeDateVC alloc] init];
        vc.goods = goods;
        fkPushNav(vc);
    }
}

#pragma mark - FKOrderDetailInfoCellDelegate
- (void)orderDetailInfoCell:(FKOrderDetailInfoCell *)cell didClickedCallBtn:(UIButton *)callBtn
{
    if (self.tel) {
        fk_call(self.tel);
    }
}

#pragma mark - 网络请求
- (void)loadData
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"order_id"] = self.order_id;
    [SVProgressHUD show];
    [FKHttpTool postWithSuffix:@"m=Home&c=OrderList&a=order_detail" param:param success:^(FKBaseResult *result) {
        [SVProgressHUD dismiss];
        if (result.isSuccess) {
            
            FKOrder *orderDetail = [FKOrder mj_objectWithKeyValues:result.data[@"list"]];
            self.tel = result.data[@"seller_tel"];
            self.orderDetail = orderDetail;
            
            NSMutableArray *datas = [NSMutableArray array];
            
            NSMutableDictionary *statusGroup = [NSMutableDictionary dictionary];
            [datas addObject:statusGroup];
            
            NSMutableDictionary *goodsGroup = [NSMutableDictionary dictionary];
            [datas addObject:goodsGroup];
            goodsGroup[@"headerH"] = @(fk_adjustW(45));
            
            NSMutableDictionary *priceInfoGroup = [NSMutableDictionary dictionary];
            [datas addObject:priceInfoGroup];
            
            NSMutableDictionary *orderInfoGroup = [NSMutableDictionary dictionary];
            [datas addObject:orderInfoGroup];
            
            NSMutableDictionary *statusItem = [NSMutableDictionary dictionary];
            statusItem[@"cellName"] = @"FKOrderDetailStatusCell";
            statusItem[@"cellH"] = @(fk_adjustW(90));
            statusItem[@"data"] = orderDetail;
            
            if ([orderDetail.item_type isEqualToString:@"1"]) { // 核销订单
                self.countDown = [orderDetail.close_time integerValue];
                if (self.countDown > 0) [self startTimer];
                
                NSMutableDictionary *contactItem = [NSMutableDictionary dictionary];
                contactItem[@"cellName"] = @"FKOrderDetailContactCell";
                contactItem[@"cellH"] = @(fk_adjustW(60));
                contactItem[@"data"] = orderDetail;
                
                statusGroup[@"items"] = @[statusItem, contactItem];
                
                NSMutableDictionary *priceInfoItem = [NSMutableDictionary dictionary];
                priceInfoItem[@"cellName"] = @"FKOrderDetailPriceInfoCell";
                priceInfoItem[@"cellH"] = @(fk_adjustW(72));
                priceInfoItem[@"data"] = orderDetail;
                
                priceInfoGroup[@"items"] = @[priceInfoItem];
                
                NSMutableDictionary *infoItem = [NSMutableDictionary dictionary];
                infoItem[@"cellName"] = @"FKOrderDetailInfoCell";
                infoItem[@"cellH"] = @(fk_adjustW(120));
                infoItem[@"data"] = orderDetail;
                
                orderInfoGroup[@"items"] = @[infoItem];
            } else { // 物流订单
                NSMutableDictionary *addressItem = [NSMutableDictionary dictionary];
                addressItem[@"cellName"] = @"FKOrderDetailAddressCell";
                addressItem[@"cellH"] = @(fk_adjustW(85));
                addressItem[@"data"] = orderDetail;
                
                NSMutableDictionary *remarkItem = [NSMutableDictionary dictionary];
                remarkItem[@"cellName"] = @"FKOrderDetailRemarkCell";
                remarkItem[@"cellH"] = @(fk_adjustW(60));
                remarkItem[@"data"] = orderDetail;
                
                statusGroup[@"items"] = @[statusItem, addressItem, remarkItem];
                
                NSMutableDictionary *priceInfoItem = [NSMutableDictionary dictionary];
                priceInfoItem[@"cellName"] = @"FKOrderDetailPriceInfoCell";
                priceInfoItem[@"cellH"] = @(fk_adjustW(92));
                priceInfoItem[@"data"] = orderDetail;
                
                priceInfoGroup[@"items"] = @[priceInfoItem];
                
                CGFloat infoCellH = 0;
                if ([orderDetail.status isEqualToString:@"10"]) { // 待支付
                    [self.btn1 setTitle:@"去支付" forState:UIControlStateNormal];
                    [self.btn1 setTitleColor:fkMainColor forState:UIControlStateNormal];
                    self.btn1.layer.borderColor = fkMainColor.CGColor;
                    [self.btn2 setTitle:@"取消订单" forState:UIControlStateNormal];
                    [self.btn2 setTitleColor:fkColor666666 forState:UIControlStateNormal];
                    self.btn2.layer.borderColor = fkColor666666.CGColor;
                    [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.bottom.offset(0);
                    }];
                    
                    infoCellH = fk_adjustW(102);
                } else if ([orderDetail.status isEqualToString:@"20"]) { // 待发货
                    
                    infoCellH = fk_adjustW(145);
                } else if ([orderDetail.status isEqualToString:@"30"]) { // 待收货
                    self.countDown = [orderDetail.order_day integerValue];
                    [self startTimer];
                    
                    [self.btn1 setTitle:@"确认收货" forState:UIControlStateNormal];
                    [self.btn1 setTitleColor:fkMainColor forState:UIControlStateNormal];
                    self.btn1.layer.borderColor = fkMainColor.CGColor;
                    [self.btn2 setTitle:@"查看物流" forState:UIControlStateNormal];
                    [self.btn2 setTitleColor:fkColor666666 forState:UIControlStateNormal];
                    self.btn2.layer.borderColor = fkColor666666.CGColor;
                    [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.bottom.offset(0);
                    }];
                    
                    infoCellH = fk_adjustW(165);
                } else if ([orderDetail.status isEqualToString:@"40"]) { // 已完成
                    [self.btn1 setTitle:@"删除订单" forState:UIControlStateNormal];
                    [self.btn1 setTitleColor:fkColor666666 forState:UIControlStateNormal];
                    self.btn1.layer.borderColor = fkColor666666.CGColor;
                    self.btn2.hidden = true;
                    [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.bottom.offset(0);
                    }];
                    
                    infoCellH = fk_adjustW(188);
                } else if ([orderDetail.status isEqualToString:@"50"]) { // 售后
                    infoCellH = fk_adjustW(188);
                } else if ([orderDetail.status isEqualToString:@"90"]) { // 已取消
                    [self.btn1 setTitle:@"删除订单" forState:UIControlStateNormal];
                    [self.btn1 setTitleColor:fkColor666666 forState:UIControlStateNormal];
                    self.btn1.layer.borderColor = fkColor666666.CGColor;
                    self.btn2.hidden = true;
                    [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.bottom.offset(0);
                    }];
                    
                    infoCellH = fk_adjustW(102);
                }
                NSMutableDictionary *infoItem = [NSMutableDictionary dictionary];
                infoItem[@"cellName"] = @"FKOrderDetailInfoCell";
                infoItem[@"cellH"] = @(infoCellH);
                infoItem[@"data"] = orderDetail;
                
                orderInfoGroup[@"items"] = @[infoItem];
            }
            
            NSMutableArray *goodsItems = [NSMutableArray array];
            for (NSInteger index = 0; index < orderDetail.goods_list.count; index++) {
                NSMutableDictionary *goodsItem = [NSMutableDictionary dictionary];
                [goodsItems addObject:goodsItem];
                goodsItem[@"cellName"] = @"FKOrderListCell";
                goodsItem[@"cellH"] = @(fk_adjustW(120));
                goodsItem[@"data"] = orderDetail.goods_list[index];
            }
            goodsGroup[@"items"] = goodsItems;
            
            self.datas = datas;
            [self.tableView reloadData];
            
//            CGFloat orderInfoH = 0;
//            if ([orderDetail.status isEqualToString:@"10"]) { // 待支付
//                [self.btn1 setTitle:@"去支付" forState:UIControlStateNormal];
//                [self.btn1 setTitleColor:fkMainColor forState:UIControlStateNormal];
//                self.btn1.layer.borderColor = fkMainColor.CGColor;
//                [self.btn2 setTitle:@"取消订单" forState:UIControlStateNormal];
//                [self.btn2 setTitleColor:fkColor666666 forState:UIControlStateNormal];
//                self.btn2.layer.borderColor = fkColor666666.CGColor;
//
//                orderInfoH = 30 * 2 + 8 + 44;
//            } else if ([orderDetail.status isEqualToString:@"20"]) { // 待发货
//                self.btn1.hidden = true;
//                self.btn2.hidden = true;
//                self.bottomView.hidden = true;
//
//                orderInfoH = 30 * 4 + 8 + 44;
//            } else if ([orderDetail.status isEqualToString:@"30"]) { // 待收货
//                [self.btn1 setTitle:@"确认收货" forState:UIControlStateNormal];
//                [self.btn1 setTitleColor:fkMainColor forState:UIControlStateNormal];
//                self.btn1.layer.borderColor = fkMainColor.CGColor;
//                [self.btn2 setTitle:@"查看物流" forState:UIControlStateNormal];
//                [self.btn2 setTitleColor:fkColor666666 forState:UIControlStateNormal];
//                self.btn2.layer.borderColor = fkColor666666.CGColor;
//
//                orderInfoH = 30 * 5 + 8 + 44;
//
//                for (FKOrderGoods *goods in orderDetail.goods_list) {
//                    goods.showRefund = true;
//                }
//            } else if ([orderDetail.status isEqualToString:@"40"]) { // 已完成
//                [self.btn1 setTitle:@"删除订单" forState:UIControlStateNormal];
//                [self.btn1 setTitleColor:fkColor666666 forState:UIControlStateNormal];
//                self.btn1.layer.borderColor = fkColor666666.CGColor;
//                self.btn2.hidden = true;
//
//                orderInfoH = 30 * 6 + 8 + 44;
//            } else if ([orderDetail.status isEqualToString:@"50"]) { // 售后
//
//            } else if ([orderDetail.status isEqualToString:@"90"]) { // 已取消
//                [self.btn1 setTitle:@"删除订单" forState:UIControlStateNormal];
//                [self.btn1 setTitleColor:fkColor666666 forState:UIControlStateNormal];
//                self.btn1.layer.borderColor = fkColor666666.CGColor;
//                self.btn2.hidden = true;
//
//                orderInfoH = 30 * 2 + 8 + 44;
//            }
            
        }
    } failure:nil];
}

#pragma mark - 商品订单操作
- (void)createPayInfo:(NSString *)payType orderSn:(NSString *)orderSn amount:(NSString *)amount pwd:(NSString *)pwd
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"payment"] = payType;
    param[@"order_sn"] = orderSn;
    param[@"password"] = pwd;
    param[@"trade_type"] = @"APP";
    [FKHttpTool postWithSuffix:@"m=Home&c=Payment&a=pay" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            if ([payType isEqualToString:@"wechat"]) {
                //                PayReq *req = [[PayReq alloc] init];
                //                req.partnerId = result.data[@"partnerid"];
                //                req.prepayId = result.data[@"prepayid"];
                //                req.nonceStr = result.data[@"noncestr"];
                //                req.timeStamp = [result.data[@"timestamp"] intValue];
                //                req.package = result.data[@"packages"]; // 这里本来是package字段的，被蠢猪后台自作主张改成了packages，害得我查了很久
                //                req.sign = result.data[@"sign"];
                //                [WXApi sendReq:req];
            } else if ([payType isEqualToString:@"alipay"]) {
                //                NSString *str = result.data[@"pay_info"];
                //                // NOTE: 调用支付结果开始支付
                //                NSString *scheme = [NSBundle mainBundle].bundleIdentifier; // 我自己直接用bundleID作为scheme了
                //                [[AlipaySDK defaultService] payOrder:str fromScheme:scheme callback:nil];
            } else {
                [SVProgressHUD showSuccessWithStatus:@"支付成功"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOrderListVC" object:nil];
            }
        }
    } failure:nil];
}

- (void)cancelGoodsOrder
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"order_id"] = self.order_id;
    [FKHttpTool postWithSuffix:@"m=App&c=KyOrder&a=cancelOrder" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD showSuccessWithStatus:@"取消成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOrderListVC" object:nil];
            fkPopVC;
        }
    } failure:nil];
}

- (void)deleteOrder
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"order_id"] = self.order_id;
    [FKHttpTool postWithSuffix:@"m=Home&c=OrderList&a=delete_order" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOrderListVC" object:nil];
            fkPopVC;
        }
    } failure:nil];
}

- (void)confirmReceive
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"order_id"] = self.order_id;
    [FKHttpTool postWithSuffix:@"m=App&c=KyOrder&a=confirmOrder" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD showSuccessWithStatus:@"确认收货成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOrderListVC" object:nil];
            fkPopVC;
        }
    } failure:nil];
}


@end
